package com.avic.rong.userOrder.activity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.avic.rong.BaseActivity;
import com.avic.rong.R;
import com.avic.rong.course.activity.CourseDetailActivity;
import com.avic.rong.payUtil.JavaPayUtil;
import com.avic.rong.payUtil.PayVo;
import com.avic.rong.userOrder.event.InformUpdate;
import com.avic.rong.userOrder.viewHolder.OrderListViewHolder;
import com.avic.rong.userOrder.adapter.OrderGoodsDetailsListAdapter;
import com.avic.rong.userOrder.adapter.OrderGoodsWeiFaHuoListAdapter;
import com.avic.rong.userOrder.adapter.PayWayAdapter;
import com.avic.rong.userOrder.api.ConfirmReceiptApi;
import com.avic.rong.userOrder.api.OrderCancelPXApi;
import com.avic.rong.userOrder.api.OrderDetailPXApi;
import com.avic.rong.userOrder.api.PaySubmitPXApi;
import com.avic.rong.userOrder.api.ToPayPXApi;
import com.avic.rong.userOrder.bean.OrderDetailsBean;
import com.avic.rong.userOrder.bean.OrderDetailsPXBean;
import com.avic.rong.userOrder.bean.PayWayBean;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.DateUtils;
import com.avic.rong.utils.DialogCustom;
import com.avic.rong.utils.GlideUtils;
import com.avic.rong.utils.MoneyShowUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.example.minato.minastore.utils.AppUtils;


import org.greenrobot.eventbus.EventBus;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

public class OrderDetailsPXActivity extends BaseActivity {

    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.tv_address_phone)
    TextView tvAddressPhone;
    @BindView(R.id.tv_address_name)
    TextView tvAddressName;
    @BindView(R.id.ll_edit_address)
    LinearLayout llEditAddress;
    @BindView(R.id.fahuo_recy_list)
    RecyclerView fahuo_recy_list;
    @BindView(R.id.tv_look_wuliu)
    TextView tv_look_wuliu;
    @BindView(R.id.tv_confirm_shouhuo)
    TextView tv_confirm_shouhuo;

    @BindView(R.id.loading_layout)
    LoadingLayout loading_layout;
    @BindView(R.id.tv_order_number)
    TextView tvOrderNumber;
    @BindView(R.id.tv_order_time)
    TextView tvOrderTime;
    @BindView(R.id.tv_order_price)
    TextView tvOrderPrice;
    @BindView(R.id.tv_pay_way)
    TextView tvPayWay;
    @BindView(R.id.tv_fapiao_type)
    TextView tvFapiaoType;
    @BindView(R.id.tv_fapiao_message)
    TextView tvFapiaoMessage;
    @BindView(R.id.tv_fapiao_taitou)
    TextView tvFapiaoTaitou;
    @BindView(R.id.tv_fapiao_start)
    TextView tvFapiaoStart;
    @BindView(R.id.tv_goods_allprice)
    TextView tvGoodsAllprice;
    @BindView(R.id.tv_youhui_price)
    TextView tvYouhuiPrice;
    @BindView(R.id.tv_member_price)
    TextView tvMemberPrice;
    @BindView(R.id.tv_yunfei_price)
    TextView tvYunfeiPrice;
    @BindView(R.id.tv_real_price)
    TextView tvRealPrice;
    @BindView(R.id.iv_order_state)
    ImageView ivOrderState;
    @BindView(R.id.tv_order_state)
    TextView tvOrderState;
    @BindView(R.id.ll_order_state)
    LinearLayout ll_order_state;
    @BindView(R.id.tv_update_fapiao)
    TextView tv_update_fapiao;
    @BindView(R.id.tv_cancel_order)
    TextView tv_cancel_order;
    @BindView(R.id.tv_look_fapiao)
    TextView tv_look_fapiao;
    @BindView(R.id.tv_urge_fahuo)
    TextView tv_urge_fahuo;
    @BindView(R.id.tv_pingjia)
    TextView tv_pingjia;
    @BindView(R.id.tv_pay)
    TextView tv_pay;
    @BindView(R.id.tv_upload_proof)
    TextView tv_upload_proof;
    @BindView(R.id.tv_again_buy)
    TextView tv_again_buy;
    @BindView(R.id.iv_photo)
    ImageView ivPhoto;
    @BindView(R.id.tv_details_title)
    TextView tv_details_title;
    @BindView(R.id.tv_goods_type)
    TextView tv_goods_type;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_order_numberpx)
    TextView tvOrderNumberpx;
    @BindView(R.id.ll_fapiao)
    LinearLayout ll_fapiao;
    @BindView(R.id.tv_apply_fapiao)
    TextView tv_apply_fapiao;
    @BindView(R.id.tv_pic_goods_type)
    TextView tvPicGoodsType;
    @BindView(R.id.tv_goods_tel)
    TextView tvGoodsTel;
    @BindView(R.id.ll_pic_tag)
    LinearLayout llPicTag;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.ll_goods_message)
    LinearLayout ll_goods_message;
    @BindView(R.id.ll_complete_hint)
    LinearLayout ll_complete_hint;


    private PopupWindow popupWindow;
    private RelativeLayout rl_close;
    private ImageView iv_goods_error;
    private RelativeLayout rl_goods_error;
    private ImageView iv_fapiao_error;
    private RelativeLayout rl_fapiao_error;
    private ImageView iv_not;
    private RelativeLayout rl_not;
    private ImageView iv_qita;
    private RelativeLayout rl_qita;
    private TextView tv_kaolv;
    private TextView tv_submit;
    private int SELECT_CHECK = -1;
    private String order_id;
    private String order_sn;


    private List<OrderDetailsBean.DeliveryListBean> deliveryList = new ArrayList<>();
    private List<OrderDetailsBean.ItemListBean> itemList = new ArrayList<>();
    private List<OrderDetailsBean.ItemListBean> itemListScreen = new ArrayList<>();
    private OrderGoodsDetailsListAdapter orderGoodsDetailsListAdapter;
    private OrderGoodsWeiFaHuoListAdapter orderGoodsWeiFaHuoListAdapter;
    private List<PayWayBean.PaymentListBean> paymentList = new ArrayList<>();

    private PayWayAdapter payWayAdapter;
    private int payId = -1;
    private boolean isAgreement = true;//勾选用户协议
    private JavaPayUtil javaPayUtil;
    private int orderType = -1;
    private int orderId = -1;
    private String orderSn = null;

    public static String ORDER_ID = "order_id";
    public static String ORDER_SN = "order_sn";
    private int COMMENT_FORCODE = 6;
    private OrderDetailsPXBean.OrderBean order;

    public static String ORDER_JUMP = "orderJump";

    private String orderMinehome;
    public static String ORDER_LIST_JUMP = "order_LIst_JUMP";
    private String orderListjump;

    private OrderDetailsPXBean.OrderBean.UserInvoiceBean userInvoice;


    @Override
    protected int getContentViewId() {
        return R.layout.activity_order_details_px;
    }

    @Override
    protected void initView() {
        ivRight.setImageResource(R.mipmap.gouwuche_dot);
        if (TextUtils.isEmpty(getIntent().getStringExtra(OrderListViewHolder.ORDER_SN))) {
            finish();
        } else {
            order_sn = getIntent().getStringExtra(OrderListViewHolder.ORDER_SN);
        }
        tvTitle.setText("订单详情");

        orderMinehome = getIntent().getStringExtra(ORDER_JUMP);
        orderListjump = getIntent().getStringExtra(ORDER_LIST_JUMP);
//        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this,
//                LinearLayoutManager.VERTICAL, false) {
//            @Override
//            public boolean canScrollVertically() {
//                return false;
//            }
//        };


        initData();
    }

    private void initData() {
        //取消订单需要刷新当前页，把底部按钮变为初始状态

        tv_look_fapiao.setVisibility(View.GONE);
        tv_look_wuliu.setVisibility(View.GONE);
        tv_confirm_shouhuo.setVisibility(View.GONE);

        tv_pingjia.setVisibility(View.GONE);
        tv_again_buy.setVisibility(View.GONE);
        tv_update_fapiao.setVisibility(View.GONE);
        tv_cancel_order.setVisibility(View.GONE);
        tv_pay.setVisibility(View.GONE);
        tv_urge_fahuo.setVisibility(View.GONE);
        tv_upload_proof.setVisibility(View.GONE);
        tv_apply_fapiao.setVisibility(View.GONE);
        ll_complete_hint.setVisibility(View.GONE);

        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> map = new HashMap<>();
            map.put("orderNumber", order_sn);
            map.put("token", getSharedPreferencesUtil().getLogintoken());
            final OrderDetailPXApi orderDetailPXApi = new OrderDetailPXApi(this, simpleOnNextListener);
            orderDetailPXApi.setCache(false);
            orderDetailPXApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(orderDetailPXApi);

            loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
                @Override
                public void onReload(View v) {
                    HttpManager.getInstance().doHttpDeal(orderDetailPXApi);
                    loading_layout.setStatus(LoadingLayout.LOADING);
                }

                @Override
                public void onReturn(View v) {
                    onBackPressed();
                }
            });
            loading_layout.setStatus(LoadingLayout.LOADING);
        } else {
            loading_layout.setStatus(LoadingLayout.EMPTY);
        }
    }

    @Override
    protected void addListener() {
        //取消订单
        tv_cancel_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancleOrder();
            }
        });
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(orderMinehome) && orderMinehome.equals("mine_home")) {
                    finish();
                } else if (!TextUtils.isEmpty(orderListjump) && orderListjump.equals("order_list")) {
                    finish();
                } else {
                    Intent intent = new Intent(OrderDetailsPXActivity.this, MineOrderActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                }
            }
        });
        ll_fapiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (userInvoice!=null){
                    Intent intent = new Intent(OrderDetailsPXActivity.this, FaPiaoDetailsActivity.class);
                    intent.putExtra("order_sn", order.getId() + "");
                    intent.putExtra("order_type", 5+ "");
                    startActivity(intent);
                }else {
                    ToastTools.showToast(OrderDetailsPXActivity.this,"您还未开票");
                }
            }
        });
        //        申请发票
        tv_apply_fapiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, UpdateFaPiaoActivity.class);
                context.startActivity(intent);
            }
        });
    }

    private void cancleOrder() {


        DialogCustom.showDoubleDialog(this, "提示", "您确定要取消订单吗？", "取消", "确定", new DialogCustom.CustomDialogDouble() {
            @Override
            public void rightButtonClicked() {
                cancleOrderReq(SELECT_CHECK);
            }

            @Override
            public void leftButtonClicked() {

            }
        });

    }

    private void cancleOrderReq(int type) {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> map = new HashMap<>();
            if (TextUtils.isEmpty(order_sn)) {
                return;
            }
            map.put("orderNumber", order_sn);
            map.put("token", getSharedPreferencesUtil().getLogintoken());

            final OrderCancelPXApi orderCancelPXApi = new OrderCancelPXApi(this, simpleOnNextListenerCancleOrderPX);
            orderCancelPXApi.setCache(false);
            orderCancelPXApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(orderCancelPXApi);

            loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
                @Override
                public void onReload(View v) {
                    HttpManager.getInstance().doHttpDeal(orderCancelPXApi);
                    loading_layout.setStatus(LoadingLayout.LOADING);
                }

                @Override
                public void onReturn(View v) {
                    onBackPressed();
                }
            });
            loading_layout.setStatus(LoadingLayout.LOADING);
        } else {
            loading_layout.setStatus(LoadingLayout.EMPTY);
        }
    }

    private void commonPop(View view) {
        popupWindow = new PopupWindow(view, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT, true);
        // 产生背景变暗效果
        WindowManager.LayoutParams lp = getWindow()
                .getAttributes();
        lp.alpha = 0.4f;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(false);
        popupWindow.setTouchable(true);
        //从下往上弹出动画效果
        popupWindow.setAnimationStyle(R.style.bottomPopupAnimation);
        popupWindow.showAtLocation(findViewById(R.id.ll_root), Gravity.BOTTOM, 0, 0);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            // 在dismiss中恢复透明度
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow()
                        .getAttributes();
                lp.alpha = 1f;
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                getWindow().setAttributes(lp);
            }
        });
    }

    //权威评测
    HttpOnNextListener simpleOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            deliveryList.clear();
            itemList.clear();
            itemListScreen.clear();
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(OrderDetailsPXActivity.this, subjects.getMsg());
                return;
            }
            loading_layout.setStatus(LoadingLayout.SUCCESS);
            if ((OrderDetailsPXBean) subjects.getData() != null) {


                OrderDetailsPXBean orderDetailsPXBean = (OrderDetailsPXBean) subjects.getData();
//                OrderDetailsBean.AddressBean address = orderDetailsPXBean.getAddress();
//                tvUserName.setText(address.getConsignee());
//                tvAddressPhone.setText(address.getTel());
//                tvAddressName.setText(address.getProvinceName() + address.getCityName() + address.getAddressName());


                order = orderDetailsPXBean.getOrder();
                tvOrderNumber.setText(order.getOrderNumber() + "");
//                List<OrderDetailsBean.OrderBean.ItemsBeanX> items = order.get();
//                String time = timeStamp2Date(order.getAddTime(),null);
                tvOrderTime.setText(order.getCreateOrderTime() + "");
                tvOrderPrice.setText("¥" + order.getThisTimePrice() + "");
                tvPayWay.setText(order.getPayWayName());

                tvRealPrice.setText("¥" + MoneyShowUtils.dealNumber(order.getShouldPayTotal() + ""));
                //总计折扣
                tvYouhuiPrice.setText("- ¥" + order.getPreferential());
                //使用余额
                tvMemberPrice.setText("- ¥" + 0.00);
                tvGoodsAllprice.setText("¥" + order.getShouldPayTotal() + "");
                tvYunfeiPrice.setText("+ ¥" + 0.00);


                OrderDetailsPXBean.OrderBean.CoursesBean courses = order.getCourses();
                if (order.getOrderType() == 0) {
//                    courseType = "点播课";
//
//                    默认图片：wwwStatic /img/online_default.jpg
                    if (TextUtils.isEmpty(courses.getCover())) {
                        GlideUtils.loaderImage(context, AppUtils.BASE_URL + "static/img/online_default.jpg", ivPhoto);
                    } else {
                        GlideUtils.loaderImage(context, orderDetailsPXBean.getFileServer() + courses.getCover(), ivPhoto);
                    }
                    tv_details_title.setText("点播课:  " + courses.getName());


                }
                if (order.getOrderType() == 1) {
//                    courseType = "直播课";
//
//                    wwwStatic /img/online_default.jpg
                    if (TextUtils.isEmpty(courses.getCover())) {
                        GlideUtils.loaderImage(context, AppUtils.BASE_URL + "static/img/online_default.jpg", ivPhoto);
                    } else {
                        GlideUtils.loaderImage(context, orderDetailsPXBean.getFileServer() + courses.getCover(), ivPhoto);
                    }
                    tv_details_title.setText("直播课:  " + courses.getName());
                }
                if (order.getOrderType() == 2) {
//                    courseType = "线下课程";
//                    默认图片：wwwStatic /img/offline_default.jpg
                    if (TextUtils.isEmpty(courses.getCover())) {
                        GlideUtils.loaderImage(context, AppUtils.BASE_URL + "static/img/offline_default.jpg", ivPhoto);
                    } else {
                        GlideUtils.loaderImage(context, orderDetailsPXBean.getFileServer() + courses.getCover(), ivPhoto);

                    }
                    tv_details_title.setText("线下课程:  " + courses.getName());
                }
                if (order.getOrderType() == 3) {
                    if (order.getCourseCustomized() != null) {
//                        courseName = order.courseCustomized.courseName;
                    }
//                    courseCover = "";
//                    courseType = "内训课";
//
//                    默认图片：wwwStatic /img/customized_default.jpg
                    if (TextUtils.isEmpty(courses.getCover())) {
                        GlideUtils.loaderImage(context, AppUtils.BASE_URL + "static/img/customized_default.jpg", ivPhoto);
                    } else {
                        GlideUtils.loaderImage(context, orderDetailsPXBean.getFileServer() + courses.getCover(), ivPhoto);

                    }
                    tv_details_title.setText("内训课:  " + courses.getName());
                } else {
                    if (order.getCourses() != null) {
//                        courseName = order.courses.name;
//                        courseCover = order.courses.cover;
//                        GlideUtils.loaderImage(context, orderDetailsPXBean.getFileServer() + courses.getCover(), ivPhoto);
                        tv_details_title.setText(courses.getName());
                    }
                }

                tvPrice.setText(order.getThisTimePrice() + "");
                tvOrderNumberpx.setText("x" + order.getAmount());
                tv_goods_type.setText(order.getOrderTypeName());


                ll_goods_message.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (TextUtils.isEmpty(order.getCourseId()+""))return;
                        if (order.getOrderType() == 0) {
                            if (TextUtils.isEmpty(courses.getCover())) {
                                context.startActivity(CourseDetailActivity.getIntent(context,courses.getType()+order.getCourseId(),AppUtils.BASE_URL + "static/img/online_default.jpg",courses.getName()));
                            } else {
                                context.startActivity(CourseDetailActivity.getIntent(context,courses.getType()+order.getCourseId(),orderDetailsPXBean.getFileServer() + courses.getCover(),courses.getName()));
                            }
                        }
                        if (order.getOrderType() == 1) {

                            if (TextUtils.isEmpty(courses.getCover())) {
                                context.startActivity(CourseDetailActivity.getIntent(context,courses.getType()+order.getCourseId(),AppUtils.BASE_URL + "static/img/online_default.jpg",courses.getName()));
                            } else {
                                context.startActivity(CourseDetailActivity.getIntent(context,courses.getType()+order.getCourseId(),orderDetailsPXBean.getFileServer() + courses.getCover(),courses.getName()));
                            }
                        }
                        if (order.getOrderType() == 2) {

                            if (TextUtils.isEmpty(courses.getCover())) {

                                context.startActivity(CourseDetailActivity.getIntent(context,courses.getType()+order.getCourseId(),AppUtils.BASE_URL + "static/img/offline_default.jpg",courses.getName()));
                            } else {
                                context.startActivity(CourseDetailActivity.getIntent(context,courses.getType()+order.getCourseId(),orderDetailsPXBean.getFileServer() + courses.getCover(),courses.getName()));

                            }
                        }
                        if (order.getOrderType() == 3) {
                            if (order.getCourseCustomized() != null) {

                            }
                            if (TextUtils.isEmpty(courses.getCover())) {
                                context.startActivity(CourseDetailActivity.getIntent(context,courses.getType()+order.getCourseId(),AppUtils.BASE_URL + "static/img/customized_default.jpg",courses.getName()));
                            } else {
                                context.startActivity(CourseDetailActivity.getIntent(context,courses.getType()+order.getCourseId(),orderDetailsPXBean.getFileServer() + courses.getCover(),courses.getName()));
                            }
                        }



                    }
                });

//                OrderDetailsBean.InvoiceBean invoice = o.getInvoice();
                userInvoice = order.getUserInvoice();
//                发票类型invType： 2：增值税专用发票  3 : 电子发票
                if (userInvoice != null) {
                    if (userInvoice.getInvType() == 2) {
                        tvFapiaoType.setText("增值税专用发票");
                    } else if (userInvoice.getInvType() == 3) {
                        tvFapiaoType.setText("电子普通发票");
                    }
                    tvFapiaoMessage.setText(userInvoice.getInvContent());
//                发票抬头invPayeeType： 1：个人  2：单位
                    if (userInvoice.getInvPayeeType() == 1) {
                        tvFapiaoTaitou.setText("个人");
                    } else if (userInvoice.getInvPayeeType() == 2) {
                        tvFapiaoTaitou.setText(userInvoice.getInvPayee());
                    }


                    if (userInvoice.getStatus() == 0&&userInvoice.getInvId()!=0) {
                        //未付款
                        tvFapiaoStart.setText("未付款");
                    } else if (userInvoice.getStatus() == 1) {
                        //已开发票
                        tvFapiaoStart.setText("已开发票");

                    } else if (userInvoice.getStatus() == 3 || userInvoice.getStatus() == 4 || userInvoice.getStatus() == 5 || userInvoice.getStatus() == 6 || userInvoice.getStatus() == 7) {
                        //开票中
                        tvFapiaoStart.setText("开票中");
                    } else if (userInvoice.getStatus() == 9 || userInvoice.getStatus() == 10 || userInvoice.getStatus() == 11 || userInvoice.getStatus() == 13) {
                        //发票红冲中
                        tvFapiaoStart.setText("发票红冲中");
                    } else if (userInvoice.getStatus() == 12) {
                        //发票已红冲
                        tvFapiaoStart.setText("发票已红冲");
                    } else if (userInvoice.getInvId()==0||userInvoice.getStatus() == 8) {
                        //无需开票
                        tvFapiaoStart.setText("无需开票");
                    }
                    ll_fapiao.setVisibility(View.VISIBLE);
                } else {
                    ll_fapiao.setVisibility(View.VISIBLE);
                }


                int payStatus = order.getPayStatus();


                if (payStatus == 0) {
//                    tradeStatus = "未支付";
                    tvOrderState.setText("订单状态:  待付款");
                    ivOrderState.setImageResource(R.mipmap.icon_daifukuan);
                    ll_order_state.setBackground(context.getResources().getDrawable(R.mipmap.ic_dai_fukuan_bg));


//                    tv_update_fapiao.setVisibility(View.VISIBLE);
//                    tv_cancel_order.setVisibility(View.VISIBLE);
//                    tv_pay.setVisibility(View.VISIBLE);
                }
                if (payStatus == 1) {
//                    tradeStatus = "交易成功";
                    tvOrderState.setText("订单状态:  交易成功");
                    ivOrderState.setImageResource(R.mipmap.icon_jiaoyi_chenggong);
                    ll_order_state.setBackground(context.getResources().getDrawable(R.mipmap.ic_jiaoyi_succeed_bg));
                    ll_complete_hint.setVisibility(View.VISIBLE);

//                    tv_pingjia.setVisibility(View.VISIBLE);
//                    tv_look_fapiao.setVisibility(View.VISIBLE);
//                    tv_again_buy.setVisibility(View.VISIBLE);
                }
                if (payStatus == 2) {
//                    tradeStatus = "审核处理中";\
                    tvOrderState.setText("订单状态:  处理中");
                    ivOrderState.setImageResource(R.mipmap.icon_jiaoyi_deal);
                    ll_order_state.setBackground(context.getResources().getDrawable(R.mipmap.ic_jiaoyi_deal_bg));
                }
                if (payStatus == 3) {
//                    tradeStatus = "交易关闭";
                    tvOrderState.setText("订单状态:  交易关闭");
                    ivOrderState.setImageResource(R.mipmap.icon_jiaoyi_guanbi);
                    ll_order_state.setBackground(context.getResources().getDrawable(R.mipmap.ic_jiaoyi_close));
                }

                if (payStatus == 0 && !"2".equals(order.getPayWay())) {
                    //去付款
                    tv_pay.setVisibility(View.VISIBLE);
                }
                if (payStatus != 1 && payStatus != 2 && payStatus != 3) {
//                    取消订单
                    tv_cancel_order.setVisibility(View.VISIBLE);
                }

                if ("2".equals(order.getPayWay())&&payStatus!=1) {
//                    上传支付凭证
                    tv_upload_proof.setVisibility(View.VISIBLE);
                }

                if (order==null)  return;
                if (payStatus == 1&&order.getTaxType()>0) {

                    if (userInvoice!=null){
                        if (!TextUtils.isEmpty(userInvoice.getInvId() + "") && userInvoice.getInvId() > 0) {
//                        查看发票
                            tv_look_fapiao.setVisibility(View.VISIBLE);
                        } else {
//                        申请发票
                            tv_apply_fapiao.setVisibility(View.VISIBLE);

                        }
                    }

                }/*else if(payStatus == 0 || payStatus == 2){
//                    修改发票
                    tv_update_fapiao.setVisibility(View.VISIBLE);
                }*/

                tv_look_fapiao.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (userInvoice!=null){
                            Intent intent = new Intent(OrderDetailsPXActivity.this, FaPiaoDetailsActivity.class);
                            intent.putExtra("order_sn", order.getId() + "");
                            intent.putExtra("order_type", 5 + "");
                            startActivity(intent);
                        }else {
                            ToastTools.showToast(OrderDetailsPXActivity.this,"您还未开票");
                        }
                    }
                });


                //去支付
                tv_pay.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (DateUtils.isFastDoubleClick())return;
                            //培训去支付

                            toPayPX(orderType, order.getOrderNumber());

                    }
                });
                //上传凭证
                tv_upload_proof.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(context, UploadProofActivity.class);
                        intent.putExtra("order_sn", order.getOrderNumber() + "");
                        intent.putExtra("orderType", 5 + "");
                        context.startActivity(intent);
                    }
                });
                //确认收货
                tv_confirm_shouhuo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        configmOrder();

                    }
                });

            }

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };

    private void configmOrder() {
        Map<String, String> map = new HashMap<>();
        if (TextUtils.isEmpty(order_sn)) return;
        map.put("orderId", order_sn + "");
        map.put("token", SharedPreferencesUtil.getInstance(context).getLogintoken());
        final ConfirmReceiptApi confirmReceiptApi = new ConfirmReceiptApi(this, simpleOnNextListenerConfimOrder);
        confirmReceiptApi.setCache(false);
        confirmReceiptApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(confirmReceiptApi);
    }

    //确认收货
    HttpOnNextListener simpleOnNextListenerConfimOrder = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }
            ToastTools.showToast(context, "收货成功");
            initData();
            InformUpdate informUpdate = new InformUpdate();
            informUpdate.setEventType(informUpdate.CONFIRM_SHOUHUO_INFORM);
            EventBus.getDefault().post(informUpdate);

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());

        }
    };

    private void toPayPX(int orderType, String orderSn) {

        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> paramsBody = new HashMap<>();
            if (TextUtils.isEmpty(orderSn)) {
                ToastTools.showToast(context, "没有获取到订单编号");
                return;
            }
            this.orderSn = orderSn;
            this.orderType = orderType;
//            paramsBody.put("orderId", orderId+"");
            paramsBody.put("token", getSharedPreferencesUtil().getLogintoken());

            //获取支付方式
            final ToPayPXApi toPayPXApi = new ToPayPXApi(this, simpleOnNextListenerPayWayPX);
            toPayPXApi.setCache(false);
            toPayPXApi.setMap(paramsBody);
            HttpManager.getInstance().doHttpDeal(toPayPXApi);


        }
    }

    private void selectPay(PayWayBean data) {



        View inflate = LayoutInflater.from(context).inflate(R.layout.select_pay_way_layout, null);
        RelativeLayout rl_close = (RelativeLayout) inflate.findViewById(R.id.rl_close);
//        final ImageView chat_btn = (ImageView) inflate.findViewById(R.id.chat_btn);
//        final ImageView ali_btn = (ImageView) inflate.findViewById(R.id.ali_btn);
//        final ImageView zhuanzhang_btn = (ImageView) inflate.findViewById(R.id.zhuanzhang_btn);
//        final ImageView yue_btn = (ImageView) inflate.findViewById(R.id.yue_btn);
//        final ImageView shop_pay_btn = (ImageView) inflate.findViewById(R.id.shop_pay_btn);
        RecyclerView recy_list = inflate.findViewById(R.id.recy_list);
        final ImageView iv_agree = (ImageView) inflate.findViewById(R.id.iv_agree);
        final TextView tv_submit_order = (TextView) inflate.findViewById(R.id.tv_submit_order);
        final TextView tv_pay_agreen = (TextView) inflate.findViewById(R.id.tv_pay_agreen);
//        final TextView tv_order_price = (TextView) inflate.findViewById(R.id.tv_order_price);
        final EditText et_use_yue = (EditText) inflate.findViewById(R.id.et_use_yue);
        final LinearLayout ll_use_yue = (LinearLayout) inflate.findViewById(R.id.ll_use_yue);

        if (order != null) {
            tv_submit_order.setText("确认付款 ¥" + MoneyShowUtils.dealNumber(order.getShouldPayTotal() + ""));
        }

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        recy_list.setLayoutManager(linearLayoutManager);
        payWayAdapter = new PayWayAdapter(context, paymentList);
        recy_list.setAdapter(payWayAdapter);
        payWayAdapter.setOrderType(5);

        //只有ordertype==4才有余额支付
        if (orderType != 5) {
            if (orderType == 4) {
                ll_use_yue.setVisibility(View.VISIBLE);
            } else {
                ll_use_yue.setVisibility(View.GONE);
            }
        } else {
            ll_use_yue.setVisibility(View.GONE);
        }


        payWayAdapter.setYueMoney(data.getUserMoney());
        payWayAdapter.setOrderPrice(order.getShouldPayTotal() + "");
        payWayAdapter.notifyDataSetChanged();


        iv_agree.setSelected(isAgreement);
//        chat_btn.setRJCPSelected(true);
        commonPop(inflate);
        //关闭按钮
        rl_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogCustom.showDoubleDialog(context, "", "确认放弃付款？", "确认离开", "继续支付", new DialogCustom.CustomDialogDouble() {
                    @Override
                    public void rightButtonClicked() {

                    }

                    @Override
                    public void leftButtonClicked() {
                       /* if (orderType!=5){
                            Intent intent = new Intent(context, OrderDetailsActivity.class);
                            intent.putExtra(ORDER_ID, orderId + "");

                            ((Activity) context).startActivityForResult(intent, COMMENT_FORCODE);
                        }else {
                            Intent intent = new Intent(context, OrderDetailsPXActivity.class);
                            intent.putExtra(ORDER_SN, orderSn + "");

                            ((Activity) context).startActivityForResult(intent, COMMENT_FORCODE);
                        }*/
                        popupWindow.dismiss();
                    }
                });
            }
        });

        //列表点击事件
        payWayAdapter.setOnClickItem(new PayWayAdapter.OnClickItem() {
            @Override
            public void OnClickListion(View view, int postion) {
                if (paymentList != null && paymentList.size() > 0) {
                    payId = paymentList.get(postion).getPayId();
                }
                payWayAdapter.setmSelectedPos(postion);
                payWayAdapter.notifyDataSetChanged();
            }
        });
        //支付协议
        tv_pay_agreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, PayAgreenActivity.class);
                context.startActivity(intent);
            }
        });
//        chat_btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                chat_btn.setRJCPSelected(true);
//                ali_btn.setRJCPSelected(false);
//                zhuanzhang_btn.setRJCPSelected(false);
//                yue_btn.setRJCPSelected(false);
//                shop_pay_btn.setRJCPSelected(false);
//                Toast.makeText(OrderConfirmActivity.this, "点击了", Toast.LENGTH_SHORT).show();
//            }
//        });
//        ali_btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                chat_btn.setRJCPSelected(false);
//                ali_btn.setRJCPSelected(true);
//                zhuanzhang_btn.setRJCPSelected(false);
//                yue_btn.setRJCPSelected(false);
//                shop_pay_btn.setRJCPSelected(false);
//            }
//        });
//        zhuanzhang_btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                chat_btn.setRJCPSelected(false);
//                ali_btn.setRJCPSelected(false);
//                zhuanzhang_btn.setRJCPSelected(true);
//                yue_btn.setRJCPSelected(false);
//                shop_pay_btn.setRJCPSelected(false);
//            }
//        });
//        yue_btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                chat_btn.setRJCPSelected(false);
//                ali_btn.setRJCPSelected(false);
//                zhuanzhang_btn.setRJCPSelected(false);
//                yue_btn.setRJCPSelected(true);
//                shop_pay_btn.setRJCPSelected(false);
//            }
//        });
//        shop_pay_btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                chat_btn.setRJCPSelected(false);
//                ali_btn.setRJCPSelected(false);
//                zhuanzhang_btn.setRJCPSelected(false);
//                yue_btn.setRJCPSelected(false);
//                shop_pay_btn.setRJCPSelected(true);
//            }
//        });
        //同意条款
        iv_agree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isAgreement = !isAgreement;
                iv_agree.setSelected(isAgreement);
            }
        });
        //付款提交
        tv_submit_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String useYue = et_use_yue.getText().toString().trim();
                String submitMoney = tv_submit_order.getText().toString().trim();
                submitMoney = submitMoney.replace("确认付款 ¥", "");
                if (Double.parseDouble(submitMoney) <= 0) {
                    if (payId == 2 || payId == 3 || payId == 4 || payId == 6) {
                        ToastTools.showLongToast(OrderDetailsPXActivity.this, "支付金额为0，请选择余额支付");
                        return;
                    }

                }
                if (!iv_agree.isSelected()) {
                    ToastTools.showLongToast(context, "同意条款才能进行支付");
                    return;
                } else if (payId != -1 && payId == 5) {
                    if (!TextUtils.isEmpty(useYue)) {
                        ToastTools.showLongToast(context, "选择余额支付后无需填写余额");
                        return;
                    }
                } else if (payId != -1 && payId != 5) {
                    if (!TextUtils.isEmpty(useYue) && !TextUtils.isEmpty(order.getShouldPayTotal() + "")) {
                        if (Double.parseDouble(useYue) > Double.parseDouble(order.getShouldPayTotal() + "")) {
                            ToastTools.showLongToast(context, "您选择了混合的支付方式，请填写正确的金额");
                            return;
                        }
                    }

                }

                paySubmitPX(useYue);


            }
        });


    }

    private void paySubmitPX(String useYue) {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> paramsBody = new HashMap<>();
            if (TextUtils.isEmpty(orderSn)) {
                ToastTools.showToast(context, "没有获取到支付ID");
                return;
            }
            paramsBody.put("orderNumber", orderSn);
            paramsBody.put("token", getSharedPreferencesUtil().getLogintoken());

            if (payId == -1) {
                return;
            }
            paramsBody.put("payId", payId + "");

            //支付提交
            final PaySubmitPXApi paySubmitPXApi = new PaySubmitPXApi(this, simpleOnNextListenerPaySubmitPX);
            paySubmitPXApi.setCache(false);
            paySubmitPXApi.setMap(paramsBody);
            HttpManager.getInstance().doHttpDeal(paySubmitPXApi);


        }

    }

    //培训支付提交
    HttpOnNextListener simpleOnNextListenerPaySubmitPX = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            paymentList.clear();
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }
            popupWindow.dismiss();
            if ((PayVo) subjects.getData() != null) {
                final PayVo payVo = (PayVo) subjects.getData();
                if (javaPayUtil == null) {
                    javaPayUtil = new JavaPayUtil(context, new JavaPayUtil.PaySuccessCallBack() {
                        @Override
                        public void paySuccess() {
//                            Intent intent = new Intent();
//                            setResult(MEMBER_REFRESH, intent);
//                            finish();
//                            ToastTools.showToast(OrderConfirmActivity.this,"支付成功");
//                            new Intent(OrderConfirmActivity.this,)
                            if (TextUtils.isEmpty(order_sn)) {
                                ToastTools.showToast(context, "没有获取到支付ID");
                                return;
                            }

//                            pay_state  1  成功   2   失败
                            Intent intent = new Intent(context, PaySucceedActivity.class);
                            intent.putExtra("order_sn", order_sn + "");
                            intent.putExtra("order_type",5);
                            intent.putExtra("pay_state",1+"");
                            context.startActivity(intent);
                        }

                        @Override
                        public void expertPaySuccess(String consultType) {

                        }

                        @Override
                        public void payCancel() {
                            if (TextUtils.isEmpty(order_sn)) {
                                ToastTools.showToast(context, "没有获取到支付ID");
                                return;
                            }

//                            pay_state  1  成功   2   失败
                            Intent intent = new Intent(context, PaySucceedActivity.class);
                            intent.putExtra("order_sn", order_sn + "");
                            intent.putExtra("order_type", 5);
                            intent.putExtra("pay_state",2+"");
                            context.startActivity(intent);
                        }
                    });
                }

                //orderType用来区分是否有余额支付
                if (orderType != -1) {
                    payVo.setOrderType(orderType);
                }
                String payId = payVo.getPayId();
                int payID = Integer.parseInt(payId);
                //payId  2  微信支付   3     支付宝     4    银行汇款/转账     6   到店支付     5   余额支付
                if (payID == 2) {
                    javaPayUtil.payByWay(payVo, "WeChat");
                } else if (payID == 3) {
                    javaPayUtil.payByWay(payVo, "Alipay");
                } else if (payID == 4) {
                    Intent intent = new Intent(context, BankPayActivity.class);
                    intent.putExtra("order_sn", order_sn + "");
                    intent.putExtra("orderType", 5 + "");
                    context.startActivity(intent);

                } else if (payID == 5) {
                    if (TextUtils.isEmpty(order_sn)) {
                        ToastTools.showToast(context, "没有获取到支付ID");
                        return;
                    }
                    Intent intent = new Intent(context, PaySucceedActivity.class);
                    intent.putExtra("order_sn", order_sn + "");
                    intent.putExtra("order_type", 5);
                    context.startActivity(intent);
                } else if (payID == 6) {
                    Intent intent = new Intent(context, ShopPayActivity.class);
                    intent.putExtra("order_sn", order_sn + "");
                    intent.putExtra("orderType", 5 );
                    context.startActivity(intent);
                }

            }
        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };
    //培训获取支付方式
    HttpOnNextListener simpleOnNextListenerPayWayPX = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            paymentList.clear();
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }

            PayWayBean data = (PayWayBean) subjects.getData();
            paymentList.addAll(data.getPaymentList());
            //选择支付
            selectPay(data);


        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };
    //权威评测
    HttpOnNextListener simpleOnNextListenerCancleOrderPX = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(OrderDetailsPXActivity.this, subjects.getMsg());
                return;
            }
            loading_layout.setStatus(LoadingLayout.SUCCESS);
            ToastTools.showToast(OrderDetailsPXActivity.this, "取消成功");

            initData();


        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };

    public static String timeStamp2Date(long time, String format) {
        if (format == null || format.isEmpty()) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(time));
    }



}
